package ydj.cloud.example.nacosgateway.util;

import ydj.cloud.example.common.exception.ApiException;
import ydj.cloud.example.common.web.ResultCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class JwtTokenUtil {

    private final static Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);

    @Value("${jwt.secret:123456}")
    private String secret;

    @Value("${jwt.tokenHeader:Authorization}")
    private String tokenHeader;

    @Value("${jwt.tokenHead:Bearer}")
    private String tokenHead;

    private Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            LOGGER.info("JWT 格式验证失败:{}", token);
        }
        return claims;
    }

    public String getUserNameFromToken(String token) {
        if (!token.startsWith(this.tokenHead)) {
            throw new ApiException(ResultCode.UNZUTHORIZED);
        }
        String authToken = token.substring(this.tokenHead.length());
        String username;
        try {
            Claims claims = getClaimsFromToken(authToken);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }
}
